package com.exercises;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Exercise350 {
    public static void main(String[] args) {

    }

    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length == 0 || nums2.length == 0) {
            return new int[]{};
        }
        if (nums1.length < nums2.length) {
            int[] a = nums1;
            nums1 = nums2;
            nums2 = a;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            int value = nums1[i];
            int count = map.get(value) == null ? 1 : map.get(value) + 1;
            map.put(value, count);
        }

        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums2.length; i++) {
            int value = nums2[i];
            Integer count = map.get(value);
            if (count == null || count == 0) {
                continue;
            } else {
                list.add(value);
                map.put(value, count - 1);
            }
        }
        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }
}

